package com.aoxin.controller.pay.weiXinNotify;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.ParserConfigurationException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.xml.sax.SAXException;

import com.aoxin.controller.html.RechargeController;
import com.aoxin.mapper.SlfRechargeMapper;
import com.aoxin.model.SlfRecharge;
import com.aoxin.service.inter.pay.PaymentService;
import com.aoxin.util.AjaxRes;
import com.aoxin.util.Const;
import com.aoxin.util.weiXinPay.xmlUntil.XMLParser;

@RestController
@RequestMapping("/weixinPayNotify")
public class WeiXinNotifyController {

        @Autowired
        private PaymentService paymentService;

        @Autowired
        private SlfRechargeMapper slfRechargeMapper;
        private Logger logger = LoggerFactory.getLogger(WeiXinNotifyController.class);
    /*  @Autowired*/
    @RequestMapping("/mobileNotify")
    @SuppressWarnings("rawtypes")
    public String mobileNotify(HttpServletRequest request, HttpServletResponse response) throws IOException, SAXException, ParserConfigurationException {
        try {
            response.sendRedirect("/slf/index.html");
        } catch (IOException e) {
            e.printStackTrace();
        }

        Integer recharge = RechargeController.recharge;
        logger.info(recharge.toString());
        Integer payStatus = this.slfRechargeMapper.getPayStatus(recharge);
        if(payStatus != null && payStatus == 1){
            return "<xml>\n" +
                    "\n" +
                    "  <return_code><![CDATA[SUCCESS]]></return_code>\n" +
                    "  <return_msg><![CDATA[OK]]></return_msg>\n" +
                    "</xml>";
        } else {
            InputStream inStream = request.getInputStream();
            ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = inStream.read(buffer)) != -1) {
                outSteam.write(buffer, 0, len);
            }
            String result  = new String(outSteam.toByteArray(),"utf-8");//获取微信调用我们notify_url的返回信息
            Map<String, Object> map = null;
            try {
                map = XMLParser.getMapFromXML(result);
                for (String key : map.keySet()){
                    System.out.println(key+"->"+map.get(key));
                }
                if (map.get("result_code").toString().equalsIgnoreCase("SUCCESS")) {
                   // String orderNo = map.get("trade_no").toString() ;
                    //订单金额
                    Integer totalFee = Integer.valueOf(map.get("total_fee").toString());
                    //应接订单金额
                    //现金支付金额
                    Integer cashFee = Integer.valueOf(map.get("cash_fee").toString());
                    //微信订单号
                    String transactionId = map.get("transaction_id").toString();
                    //商户订单号
                    String outTradeNo = map.get("out_trade_no").toString();
                    //支付完成时间
                    String timeEnd = map.get("time_end").toString();
                    System.out.println(timeEnd);
                    //业务逻辑 todo
                    String[] mapstring=map.get("attach").toString().split("&");
                    
                    Integer userId = Integer.valueOf(mapstring[0]);
                    Integer thresholdId=Integer.valueOf(mapstring[1]);
                    SlfRecharge slfRecharge = new SlfRecharge();
                    slfRecharge.setMoney(new BigDecimal(totalFee/100));
                    slfRecharge.setRecharge(recharge);
                    slfRecharge.setOrderNumber(outTradeNo);
                    slfRecharge.setOrderId(transactionId);
                    slfRecharge.setReallyTotalMoney(new BigDecimal(cashFee/100));
                    this.paymentService.updateSynthesizeData(slfRecharge,userId,thresholdId);

                }
                outSteam.close();
                inStream.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return "<xml>\n" +
                "\n" +
                "  <return_code><![CDATA[SUCCESS]]></return_code>\n" +
                "  <return_msg><![CDATA[OK]]></return_msg>\n" +
                "</xml>";
    }
    
    
    
    
    
    
    
  /*  @RequestMapping("/updateSynthesizeData")
    public String updateSynthesizeData(SlfRecharge slfRecharge,Integer userId,Integer thresholdId){
    	this.paymentService.updateSynthesizeData(slfRecharge,userId,thresholdId);
    	return "2222";
    }*/
    
    
    
    @RequestMapping("/isFirstCharge")
    public AjaxRes isFirstCharge(AjaxRes res,Integer firstChargeThresholdId){
    	try {
    		boolean flag=paymentService.isFirstCharge(firstChargeThresholdId);
    		res.setSucceed(flag,Const.DATA_SUCCEED);
		} catch (Exception e) {
			res.setFailMsg(e.getMessage());
		}
    	return res;
    }
    
    @RequestMapping("/queryFirstChargeThreshold")
    public AjaxRes queryFirstChargeThreshold(AjaxRes res){
    	try {
    		List<Map<String,Object>> firstChargeThreshold=paymentService.queryFirstChargeThreshold();
    		res.setSucceed(firstChargeThreshold,Const.DATA_SUCCEED);
		} catch (Exception e) {
			res.setFailMsg(e.getMessage());
		}
    	return res;
    }
    
    
    
    
    
}
